﻿using SrBBSPro.Util;
using SrBBSPro.Entities;
using SrBBSPro.Services;
using SrBBSPro.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SrBBSPro.Services.Messaging;
using System.IO;
using SrBBSPro.BaseClasses;

namespace SrBBSPro.Controllers
{
    public class AccountController : BaseController
    {
        #region Views
        public ActionResult Index()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);
            return View(user);
        }
        //登录
        [AllowAnonymous]
        public ActionResult Login()
        {
            //如果已经登录，直接跳转至主页
            if (HttpContext.User.Identity.IsAuthenticated)
                return RedirectToAction("Index", "Account");

            var cookie = Request.Cookies["StaffNo"];
            if (cookie != null)
            {
                ViewBag.StaffNo = cookie.Value;
            }

            return View();
        }
        //注册 
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }
        //忘记密码
        [AllowAnonymous]
        public ActionResult Forget()
        {
            return View();
        }
        //帐号设置
        public ActionResult Set()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);
            return View(user);
        }
        
        //用户主页
        public ActionResult Home()
        {
            var user = new UserService().GetUserInfo(CurrentUserId);

            var posts = new PostService().GetPagePostsByFilter(new GetPagePostsRequest(1, 30) { UserId = CurrentUserId });
            if (posts.IsSuccess)
                ViewBag.MyPosts = posts.Pages.Items; //最近求解
            var answers = new CommentService().GetPageCommentsByUserId(1, 30, CurrentUserId);
            if (answers.IsSuccess)
                ViewBag.MyAnswers = answers.Pages.Items;//最近回答 最新的30条
            return View(user);
        }

        //搜索@
        [AllowAnonymous]
        public ActionResult Jump(string StaffName)
        {
            var user = new UserService().GetUserByStaffName(StaffName);
            if (user == null)
                return Redirect("~/error/404");

            var posts = new PostService().GetPagePostsByFilter(new GetPagePostsRequest(1, 30) { UserId = user.Id });
            if (posts.IsSuccess)
                ViewBag.MyPosts = posts.Pages.Items; //最近求解
            var answers = new CommentService().GetPageCommentsByUserId(1, 30, user.Id);
            if (answers.IsSuccess)
                ViewBag.MyAnswers = answers.Pages.Items;//最近回答 最新的30条            
            return View("Home",user);
        }
       
        //我的消息 
        public ActionResult Message()
        {
            return View();
        }
        //注销登录
        public ActionResult LogOut()
        {
            new AspFormsAuthentication().SignOut();
            Session.Clear();
            return RedirectToAction("Index", "Home");
        }
        #endregion


        #region Handler
        ///user/upload/
        //上传图片
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase f)
        {
            try
            {
                var files = Request.Files;
                if (files.Count == 0)
                    return Json(new
                    {
                        status = 1,
                        msg = "请选择要修改的头像"
                    });
                var curFile = files[0];
                if ((curFile.ContentLength / 1024) > 30)
                {
                    return Json(new
                    {
                        status = 1,
                        msg = "请选择小于30KB的图片."
                    });
                }

                //获取保存路径
                var filesUrl = Server.MapPath("~/Content/images/HeadPortraits/");
                if (Directory.Exists(filesUrl) == false)//路径不存在则创建
                    Directory.CreateDirectory(filesUrl);
                var fileName = Path.GetFileName(curFile.FileName);
                //文件后缀名
                var filePostfixName = fileName.Substring(fileName.LastIndexOf('.'));
                //新文件名
                var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + filePostfixName;
                var path = Path.Combine(filesUrl, newFileName);
                //保存文件
                curFile.SaveAs(path);

                var newPath = "/Content/images/HeadPortraits/" + newFileName;

                new UserService().UpdateHeadPortrait(newPath, CurrentUserId);

                return Json(new
                {
                    status = 0,
                    msg = "上传成功",
                    url = newPath
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    status = 1,
                    msg = "上传失败、错误信息：" + ex.Message
                });
            }
        }
        //登录
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public ActionResult Login(LoginModel model)
        {
            if (model == null)
                return JsonResult(false, "请勿传递非法参数，请刷新重试！");

            var userService = new UserService();

            var entity = userService.Login(model.StaffNo);
            if (entity == null)
            {
                return JsonResult(false, "用户不存在。");
            }
            if (entity.Password != model.Pass)
            {
                return JsonResult(false, "用户名或密码输错了呢。");
            }
            if (entity.IsDisabled)
            {
                return JsonResult(false, "你的帐号已被封，请联系管理员。");
            }
            new AspFormsAuthentication().SetAuthenticationToken(entity.Id + "$" + entity.StaffName + "$" + entity.IsAdmin);
            HttpCookie cookie = new HttpCookie("StaffNo");
            cookie.Value = entity.Id;
            cookie.Expires = DateTime.Now.AddDays(5);
            Session["IsAdmin"] =  entity.IsAdmin;
            Response.Cookies.Set(cookie);
            entity.Password = "";
            return JsonResult(true, "登录成功。", new { user = entity });
        }
        //注册
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public ActionResult Register(RegisterModel model)
        {
            if (model == null)
                return JsonResult(false, "请勿传递非法参数，请刷新重试！");

            var service = new UserService();
            if (service.CheckStaffNoIsExists(model.Id))
                return JsonResult(false, "该工号已被注册！");
            if (service.CheckStaffNameIsExists(model.StaffName))
                return JsonResult(false, "该姓名已被使用！");


            var entity = new User
            {
                Id = model.Id,
                Password = model.Pass,
                StaffName = model.StaffName,
                Gender = model.Gender,
                HeadPortrait = GetFileName(),
                VipLevel = -1,
                Depart =model.Depart,
                CreateTime = DateTime.Now,
                Integral = 200,//注册时送200积分
            };

            var response = service.Insert(entity);
            return JsonResult(response.IsSuccess, response.Message);
        }
        //设置
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Set(SetModel model)
        {
            if (model == null)
                return JsonResultForFly(1, "请勿传递非法参数，请刷新重试！");

            var service = new UserService();
            var user = service.GetUserInfo(CurrentUserId);           
            user.StaffName = model.StaffName;
            user.Gender = model.Gender;
            user.Depart = model.Depart;
            user.Sign = model.Sign;
            var response = service.Update(user);
            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //修改密码
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Repass(RepassModel model)
        {
            if (model == null)
                return JsonResultForFly(1, "请勿传递非法参数，请刷新重试！");

            var service = new UserService();

            var user = service.GetUserInfo(CurrentUserId);
            if (user.Password != model.NowPass)
                return JsonResultForFly(1, "原密码输入错误，请重试！");

            user.Password = model.Pass;

            var response = service.Update(user);

            if (response.IsSuccess)
                return JsonResultForFly(0, "修改成功，下次登录生效！", "/user/");

            return JsonResultForFly(1, "修改失败，请重试！");
        }


        public ActionResult List()
            => View();
        
        public ActionResult UserList()
            => JsonResultForLay<User,string>(new UserService().GetUserList(Request["dep"]),0,false);
        #endregion

        /// <summary>
        /// 获取指定文件
        /// </summary>
        /// <returns></returns>
        private string GetFileName()
            => "/Content/images/default.png";

    }
}